package dao.impl;

import dao.StudentDao;
import entity.Student;

import java.io.*;

public class StudentDaoImpl implements StudentDao {
    @Override
    public void addStudent(Student student) {
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("student.txt", true))) {
            bufferedWriter.write(student.toString());
            bufferedWriter.newLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean isExist(Student student) {
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader("student.txt"))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.equals(student.toString())) {
                    throw new RuntimeException("该学生已存在");
                }
                String[] studentInfo = line.split("-");
                if (studentInfo[3].equals(student.getEmail())) {
                    throw new RuntimeException("该邮箱已存在");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}
